package com.shengyuan.manage_os.ui;

import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shengyuan.manage_os.R;
import com.shengyuan.manage_os.im.ECApplication;
import com.shengyuan.manage_os.im.common.utils.ToastUtil;
import com.shengyuan.manage_os.im.ui.LauncherActivity;
import com.shengyuan.manage_os.im.ui.SDKCoreHelper;
import com.shengyuan.manage_os.im.ui.group.CreateGroupActivity;
import com.shengyuan.manage_os.im.ui.settings.SettingsActivity;
import com.shengyuan.manage_os.old.ying.boce.jsy.UpdateManager;
import com.shengyuan.manage_os.old.ying.boce.task.GenericTask;
import com.shengyuan.manage_os.old.ying.boce.task.TaskAdapter;
import com.shengyuan.manage_os.old.ying.boce.task.TaskListener;
import com.shengyuan.manage_os.old.ying.boce.task.TaskParams;
import com.shengyuan.manage_os.old.ying.boce.task.TaskResult;
import com.shengyuan.manage_os.old.ying.erpm.LoginActivity;
import com.shengyuan.manage_os.old.ying.erpm.MainApplication;
import com.shengyuan.manage_os.old.ying.erpm.tasks.SubmitUpdateTask;
import com.shengyuan.manage_os.old.ying.erpm.util.SharePreferenceUtil;
import com.shengyuan.manage_os.old.ying.erpm.util.Utility;
import com.shengyuan.manage_os.ui.fragment.ContactFragment;
import com.shengyuan.manage_os.ui.fragment.MessageFragment;
import com.shengyuan.manage_os.ui.fragment.MyselfFragment;
import com.shengyuan.manage_os.ui.fragment.WorkFragment;
import com.shengyuan.manage_os.utils.EquipParam;
import com.shengyuan.manage_os.utils.ViewTools;
import com.shengyuan.manage_os.view.CustomButton;

import org.json.JSONObject;

import static com.shengyuan.manage_os.old.ying.erpm.MainApplication.CheckDirectory;

/**
 * Created by Administrator on 2016/8/4.
 * 这个页面用于呈现主页面
 */
public class MainActivity extends LauncherActivity implements View.OnClickListener {

    private ImageView img_add;
    private LinearLayout  button_dynamic;
    private CustomButton button_msg, button_work, button_contact, button_myself;
    private CustomButton[] buttons = new CustomButton[4];
    private Fragment currentFragment;
    private MessageFragment messageFragment;
    private WorkFragment workFragment;
    private MyselfFragment myselfFragment;
    private ContactFragment contactFragment;
    private View view;
    private RelativeLayout img_tab;
    private TextView tv_tab;


    public static Activity activity;

    public static String OWN_HEADER_URL = "";
    private SettingsActivity settingsActivity = null;

    private static MainActivity mainActivity;

    public static MainActivity getInstance() {
        if (mainActivity == null) {
            mainActivity = new MainActivity();
        }
        return mainActivity;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置状态栏为透明
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        setContentView(R.layout.activity_main);
        EquipParam.init(this);
        activity = this;
        img_tab = (RelativeLayout)findViewById(R.id.img_tab);
        tv_tab = (TextView)findViewById(R.id.tv_tab);
        new SettingsActivity().setFinishActivity(new SettingsActivity.FinishActivityListener() {
            @Override
            public void finish() {
                MainActivity.this.finish();
                settingsActivity = null;
            }
        });
        ViewTools viewTools = new ViewTools();
        viewTools.setOnClickPopWindowItemListener(new ViewTools.OnClickPopWindowItemListener() {
            @Override
            public void onClick(int itemID) {
                switch (itemID){
//                    case R.id.tv_3:
//                        Intent intent = new Intent(MainActivity.this,AddFirendActivity.class);
//                        startActivity(intent);
//                        break;
                    case R.id.tv_2:
                        startActivity(new Intent(MainActivity.this, CreateGroupActivity.class));
                        break;
                    default:
                        Utility.MessageBox(MainActivity.this,"此功能暂时没有开发");
                        break;
                }
//                    Utility.MessageBox(MainActivity.this,"此功能暂时没有开发");
            }
        });

//        bottom = (LinearLayout) findViewById(R.id.bottom);
        initView();

        ViewTools.showView(button_msg, buttons);
        messageFragment = new MessageFragment();
        messageFragment.switchFrament(messageFragment,currentFragment);
//        messageFragment.addFrament(R.id.fragment_content,messageFragment,"MESSAGE");
        currentFragment = messageFragment;
        button_msg.setOnClickListener(this);
        button_work.setOnClickListener(this);
        button_dynamic.setOnClickListener(this);
        button_contact.setOnClickListener(this);
        button_myself.setOnClickListener(this);
        img_add.setOnClickListener(this);



        if (!checkPermission("android.permission-group.LOCATION"))
            requestPermission(new String[]{"android.permission-group.LOCATION"},0x00000020);

        if (!checkPermission("android.permission.CAMERA"))
            requestPermission(new String[]{"android.permission.CAMERA"},0x00000030);

        if (!checkPermission("android.permission-group.STORAGE"))
            requestPermission(new String[]{"android.permission-group.STORAGE"},100);
        else {
            CheckDirectory();
        }


        updateSystem();

    }

    public void updateSystem() {
        if (LoginActivity.pmUser!=null && LoginActivity.pmUser.UserName!=null) {
            SubmitUpdateTask mSubmitTask = new SubmitUpdateTask();
            mSubmitTask.setListener(mTaskListener_UpdateFile);
            TaskParams params = new TaskParams();
            params.put(SubmitUpdateTask.UPDATEFILE,
                    MainApplication.updatefile);

            mSubmitTask.execute(params);
        }
    }


    public TaskListener mTaskListener_UpdateFile = new TaskAdapter() {
        public ProgressDialog mDialog;
        @Override
        public void onPostExecute(GenericTask task, TaskResult result) {
            try {
                if(mDialog!=null)mDialog.dismiss();
                SubmitUpdateTask t = (SubmitUpdateTask)task;
                if (result == TaskResult.OK) {
                    Utility.MessageBox(MainActivity.this,getString(R.string.setting_success_system_data));
                    UpdateManager manager = new UpdateManager(MainActivity.this);
                    // 检查软件更新
                    manager.UPDATEFILE = ECApplication.updatefile;
                    manager.checkUpdate();
                } else {
                    Utility.MessageBox(MainActivity.this,t.getMsg());
                }
            } catch (Exception e) {
            }

        }

        @Override
        public void onCancelled(GenericTask task) {
//			try {
//				mDialog.dismiss();
//				mDialog = null;
//				fff = true;
//			} catch (Exception e) {
//			}
        }

        @Override
        public void onPreExecute(GenericTask task) {
            //mDialog = Utility.ShowModelDialog(ECApplication.Instance, getString(R.string.setting_system_update));
            //mDialog.show();
        }
    };


    public boolean checkPermission(String Permission){

        boolean isHasPermission = ContextCompat.checkSelfPermission(this, Permission)
                != PackageManager.PERMISSION_GRANTED;
        return isHasPermission;
    }

    public void requestPermission(String[] Permission,int permsRequestCode){

        ActivityCompat.requestPermissions(this,Permission, permsRequestCode);
    }

    @Override
    public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults){


        boolean permission = grantResults[0]==PackageManager.PERMISSION_GRANTED;
        if (permission) {
            switch (permsRequestCode){
                case 0xfffff200:
                    System.out.println("&&&&&&*****====授权成功");
                    break;
                case 0xfffff300:
                    System.out.println("&&&&&&*****====授权成功");
                    break;
                case 100:
                    CheckDirectory();
                    System.out.println("&&&&&&*****"+permissions[0]+"====授权成功");
                    break;
            }
        }else {
            System.out.println("&&&&&&*****====授权失败");
        }

    }





    @Override
    protected void onDestroy() {
        super.onDestroy();
        contactFragment = null;
        currentFragment = null;
        workFragment = null;
        myselfFragment = null;
        messageFragment = null;
        System.out.println("Conversation====+++++++++onDestroy");
    }


    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    void initView() {
        button_msg = (CustomButton) findViewById(R.id.main_msg);
        button_work = (CustomButton) findViewById(R.id.main_work);
        button_dynamic = (LinearLayout) findViewById(R.id.main_dynamic);
        button_contact = (CustomButton) findViewById(R.id.main_contact);
        button_myself = (CustomButton) findViewById(R.id.main_myself);
//        total = (TextView) findViewById(R.id.message_total);
        img_add = (ImageView) findViewById(R.id.img_add);
//        img_call = (ImageView) findViewById(R.id.img_call);
        buttons[0] = button_msg;
        buttons[1] = button_work;
        buttons[2] = button_contact;
        buttons[3] = button_myself;
        button_msg.setBackgroundResource(R.drawable.tab_home);
        button_contact.setBackgroundResource(R.drawable.tab_find);
        button_myself.setBackgroundResource(R.drawable.tab_mine);
        button_work.setBackgroundResource(R.drawable.tab_frend);
        button_msg.setText("消息");
        button_work.setText("工作");
        button_contact.setText("联系人");
        button_myself.setText("我的");
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_msg:
                ViewTools.showView(button_msg, buttons);
                ViewTools.changeTitle(img_tab,tv_tab,null,1);
                if(messageFragment == null){
                    messageFragment = new MessageFragment();
                }
                messageFragment.switchFrament(messageFragment,currentFragment);
//                messageFragment.replayFragment(R.id.fragment_content,currentFragment,messageFragment,"MESSAGE");
                currentFragment = messageFragment;
                break;
            case R.id.main_work:
                ViewTools.showView(button_work, buttons);
                ViewTools.changeTitle(img_tab,tv_tab,"工作",2);
               if(workFragment == null){
                   workFragment = new WorkFragment();
               }

                workFragment.switchFrament(workFragment,currentFragment);
//                workFragment.replayFragment(R.id.fragment_content,currentFragment,workFragment,"WORK");
                currentFragment = workFragment;
                break;
            case R.id.main_dynamic:

                    Intent intent1 = new Intent(MainActivity.this, MomentsActivity.class);
                    startActivity(intent1);
//                }
                break;
//            //发现
            case R.id.main_contact:
                ViewTools.showView(button_contact, buttons);
                ViewTools.changeTitle(img_tab,tv_tab,"联系人",2);
                if(contactFragment == null){
                    contactFragment = new ContactFragment();
                }
//                contactFragment.replayFragment(R.id.fragment_content,currentFragment,contactFragment,"CONTACT");
                contactFragment.switchFrament(contactFragment,currentFragment);
                currentFragment = contactFragment;
                break;
//            //发图询价
            case R.id.main_myself:
                ViewTools.showView(button_myself, buttons);
                ViewTools.changeTitle(img_tab,tv_tab,"我的",2);
                if(myselfFragment == null){
                    myselfFragment = new MyselfFragment();
                }
                myselfFragment.switchFrament(myselfFragment,currentFragment);
//                myselfFragment.replayFragment(R.id.fragment_content,currentFragment,myselfFragment,"MYSELF");
                currentFragment = myselfFragment;
                break;
//            //我的
            case R.id.img_add:
                ViewTools.showSetting(this,v,550,600,1,null);
                break;
        }
    }


}
